/* -*- mode: c++; coding: utf-8-unix -*-
 */

#ifndef _AUTOFREE
#define _AUTOFREE


// Hack to overcome implicit conversion problem of g_free
template <class T>
inline void gfree(T* ptr) { g_free(ptr); }

template <class T, void (*delfun)(T*)>
class autofree
{
	T* _ptr;

	inline void Copy(autofree &o) { if (&o != this) reset(o.release()); }
public:
	explicit autofree(T *ptr = 0) : _ptr(ptr) {}
	~autofree() { reset(); }

	autofree(const autofree &o) { Copy(o); }
	autofree& operator=(const autofree &o)
	{
		Copy(o);
		return *this;
	}

	inline operator T*() const { return _ptr; }
	inline T* operator*() const { return _ptr; }
	inline T* get() const { return _ptr; }
	inline T* operator->() { return _ptr; }
	inline void reset(T* ptr = 0)
	{
		if (_ptr) delfun(_ptr);
		_ptr = ptr;
	}
	inline T* release()
	{
		T* p = _ptr;
		_ptr = 0;
		return p;
	}
};

#endif //_AUTOFREE
